package com.epalmpay.service.yunstream.impl;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.*;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.PayTransferResult;
import com.epalmpay.payplat.result.PayWithdrawalResult;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.yunstream.IAppPayService;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.payplat.UtilFun;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import me.chanjar.weixin.common.exception.WxErrorException;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("appPayService")
public class AppPayServiceImpl implements IAppPayService {
	@Resource
	private OrderShopMapper orderShopMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource 
	private GroupPayconfigMapper groupPayconfigMapper;
	@Resource
	private MemberCardMapper memberCardMapper;
	@Resource
	private OrderServiceGoodMapper orderServiceGoodMapper;
	@Resource
	private MallGoodMapper mallGoodMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private MemberGradeMapper memberGradeMapper;
	@Resource
	private OrderGoodMapper orderGoodMapper;
	@Resource
	private DeviceMapper deviceMapper;
	@Resource
	private DeviceDeskCardMapper deviceDeskCardMapper;
	@Resource
    private ShopMapper shopMapper;
	@Resource
	private PrePurchaseActivityMapper prePurchaseActivityMapper;
	@Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	private PrePurchaseMoneyChangeMapper prePurchaseMoneyChangeMapper;
	@Resource
	private AgentMapper agentMapper;
	@Resource
	private IMemberService memberService;
	
	@Resource
	private IWalletService walletService;
	
	@Resource
	private  IProfitStatisService profitStatisService;
	
	private Logger logger = LoggerFactory.getLogger(AppPayServiceImpl.class);

	@Override
	public Response updateWeiXinPay(String memberId, Integer goodsOrderPrice, String ip,String homeUrl) throws ApplicationException{
		Map<String, Object> result = new HashMap<String, Object>();
		Member member=memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
		if (member==null) {
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		if (groupPayconfig==null) {
			throw new ApplicationException(Rescode.FAIL, "商户参数未配置");
		}
		String orgOrderNum = UtilFun.createOrderNum();
		String payOrderid=Const.APP_RECHARGE+orgOrderNum;
			 //插入线下交易表
	        TradeOffline record = new TradeOffline();
	        record.setMemo("云流-钱包微信充值");
		    record.setDetail("云流-钱包微信充值");//详情
		    record.setTransactionType((byte)BizEnum.TransactionType.Recharge.getType());
		    record.setGmtCreate(new Date());
	        record.setGmtModified(new Date());
	        record.setGroupId(member.getGroupId());
	        record.setOrderId(orgOrderNum); 
	        record.setPayerId(member.getId());//会员id
	        record.setPayerName(member.getName());
	        record.setPayerType((byte) CommonEnum.UserType.User.getType());
	        record.setReceiverId(memberId);//接收者id
	        record.setReceiverName(member.getName());//接收者
			record.setReceiverType((byte) CommonEnum.UserType.User.getType());
	        record.setSubType((byte)BizEnum.PaymentScene.AppOut.getType());//支付场景
	        record.setOrderAmount(goodsOrderPrice); 
	        record.setDiscountAmount(0);//折扣金额
	        record.setRealAmount(record.getOrderAmount());//实付金额
	        record.setPayType((byte)BizEnum.PaymentType.WebChat.getType());
	        record.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());
	        record.setIsWallet(true);
	        record.setTermSerial(null);
	        record.setMerchantNo(null);//商户号
	        record.setTerminalNo(null);//商户终端号
	        record.setTransNo(null); //交易流水号
	        record.setTransOrderNo(null);//交易机构订单号
	        record.setPayAccount("");//支付卡号
	        record.setScanOrganization(null);//扫码付入网机构
	        record.setCrcodeStr(null); 
	        record.setOldOrderId(null); 
	        record.setDividableAmount(0);//可分润金额
	        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
	        record.setPayOrderid(payOrderid);
	        record.setPayBakOrderid(null);
	        record.setInNetCompany(null);//入网机构
	        tradeOfflineMapper.insertSelective(record);
	        //微信原生支付调用
		WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
		String nonce_str = RandomStringUtils.randomAlphanumeric(28);
		orderRequest.setNonceStr(nonce_str);
		orderRequest.setDeviceInfo("WEB");
		orderRequest.setBody("云流-钱包充值");
		orderRequest.setOutTradeNo(payOrderid);
		orderRequest.setTotalFee(goodsOrderPrice);// 单位分
		orderRequest.setSpbillCreateIp(ip);// IP
		String notifyURL=homeUrl+Const.WXCHARGE_NOTIFY_URL;
		orderRequest.setNotifyURL(notifyURL);//回调地址
		orderRequest.setTradeType("APP");// JSAPI，NATIVE，APP，WAP
		WxPayService wxPayService = new WxPayServiceImpl(); 
		WxPayConfig wxPayConfig=new WxPayConfig();
		wxPayConfig.setAppId(groupPayconfig.getWxAppid()); 
		wxPayConfig.setMchId(groupPayconfig.getWxMerchantno()); 
		wxPayConfig.setMchKey(groupPayconfig.getWxPayKey());
		wxPayService.setConfig(wxPayConfig);
		try {
			WxPayUnifiedOrderResult unifiedorderResult = wxPayService.unifiedOrder(orderRequest);
			if ("SUCCESS".equals(unifiedorderResult.getReturnCode())) {
				if ("SUCCESS".equals(unifiedorderResult.getResultCode())) {
					result.put("appid", unifiedorderResult.getAppid());
					result.put("mch_id", unifiedorderResult.getMchId());
					result.put("nonce_str", unifiedorderResult.getNonceStr());
					result.put("sign", unifiedorderResult.getSign());
					result.put("prepay_id", unifiedorderResult.getPrepayId());
					result.put("trade_type", unifiedorderResult.getTradeType());
					result.put("orgOrderNum", orgOrderNum);
					result.put("orderAmount", goodsOrderPrice);
					return Response.getSuccess(result); 
				} else {
					throw new ApplicationException(unifiedorderResult.getResultCode(), unifiedorderResult.getErrCodeDes());
				}
			}
		} catch (WxErrorException e) {
			throw new ApplicationException(Rescode.FAIL, "统一下单出现异常");
		}
		return null;
	}

	@Override
	public Response updateAliPay(String memberId, Integer goodsOrderPrice)
			throws ApplicationException {
		Member member=memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
		if (member==null) {
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		if (groupPayconfig==null) {
			throw new ApplicationException(Rescode.FAIL, "商户参数未配置");
		}
		String orgOrderNum = UtilFun.createOrderNum();
		String payOrderid=Const.APP_RECHARGE+orgOrderNum;
			 //插入线下交易表
	        TradeOffline record = new TradeOffline();
	        record.setMemo("云流-钱包支付宝充值");
		    record.setDetail("云流-钱包支付宝充值");//详情
		    record.setTransactionType((byte)BizEnum.TransactionType.Recharge.getType());
		    record.setGmtCreate(new Date());
	        record.setGmtModified(new Date());
	        record.setGroupId(member.getGroupId());
	        record.setOrderId(orgOrderNum); 
	        record.setPayerId(member.getId());//会员id
	        record.setPayerName(member.getName());
	        record.setPayerType((byte) CommonEnum.UserType.User.getType());
	        record.setReceiverId(memberId);//接收者id
	        record.setReceiverName(member.getName());//接收者
			record.setReceiverType((byte) CommonEnum.UserType.User.getType());
	        record.setSubType((byte)BizEnum.PaymentScene.AppOut.getType());//支付场景
	        record.setOrderAmount(goodsOrderPrice); 
	        record.setDiscountAmount(0);//折扣金额
	        record.setRealAmount(record.getOrderAmount());//实付金额
	        record.setPayType((byte)BizEnum.PaymentType.AliPay.getType());
	        record.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());
	        record.setIsWallet(true);
	        record.setTermSerial(null);
	        record.setMerchantNo(null);//商户号
	        record.setTerminalNo(null);//商户终端号
	        record.setTransNo(null); //交易流水号
	        record.setTransOrderNo(null);//交易机构订单号
	        record.setPayAccount("");//支付卡号
	        record.setScanOrganization(null);//扫码付入网机构
	        record.setCrcodeStr(null); 
	        record.setOldOrderId(null); 
	        record.setDividableAmount(0);//可分润金额
	        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
	        record.setPayOrderid(payOrderid);// CZW钱包充值
	        record.setPayBakOrderid(null);
	        record.setInNetCompany(null);//入网机构
	        tradeOfflineMapper.insertSelective(record);
	        return Response.getSuccess(payOrderid);
	}

	@Override
	public Map<String, Object> insertBankCardVefity(String memberId, String tranAmt, String bankCode, String accNo,
			String accName, String certNo, String mobile, String cardCvn, String cardExpdate, String ip) throws ApplicationException {
		Map<String, Object> result = new HashMap<String, Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		//校验卡是否支持绑定 提高绑卡成功率  
		Map<String, String> mapCardNum=IPayAPI.queryCardCodeNew(accNo);
		if(!mapCardNum.get("Rcd").equals("0000")){
			throw new ApplicationException(Rescode.FAIL, "该卡暂不支持快捷绑定,请换张卡再试");
		}
		//中信银行出错
		if(!mapCardNum.get("InsCd").startsWith(bankCode.substring(0,6))){ 
			throw new ApplicationException(Rescode.FAIL, "您输入的卡号是"+mapCardNum.get("Cnm"));
		}
		MemberCard memberCardName=memberCardMapper.selectByPrimaryName(Long.parseLong(memberId));
		if(memberCardName!=null&&!memberCardName.getIdName().equals(accName)){
			throw new ApplicationException(Rescode.FAIL, "此卡认证信息与初次认证信息不匹配");
		}
		
		//验证该卡是否绑定过
	//	MemberCard memberCard =  memberCardMapper.selectOneSuccessByMemberId(Long.parseLong(memberId),accNo,bankCode,BizEnum.BindCardType.QuickPayCard.getType());
		int cardType=BizEnum.CardType.DebitCard.getType();
		String cvnStr=null;
		//此处调用绑卡接口
		if(Tools.notEmpty(cardCvn)&&Tools.notEmpty(cardExpdate)){
			cardType=BizEnum.CardType.CreditCard.getType();
			cvnStr=cardCvn+";"+cardExpdate;
		}
		
		//验证该卡是否绑定过
		MemberCard memberCard =  memberCardMapper.selectCardNum(Long.parseLong(memberId),accNo,bankCode);
		
		if(memberCard==null){
			MemberCard record = new MemberCard();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setMemberId(Long.parseLong(memberId));
			record.setBankIntegral(bankCode);
			record.setCardNum(accNo);
			record.setIdName(accName);
			record.setIdNo(certNo);
			record.setCardMobile(mobile);
			record.setCardType(cardType); 
			record.setCardCvn(cardCvn);
			record.setCardExpdate(cardExpdate);
			record.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
			record.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
			record.setBankZone(null);//开户地区
			bankDesc(record, bankCode); 
		    memberCardMapper.insert(record);
		    result.put("cardId", record.getId());//返回卡id 便于重复发送验证码
				    if(member.getIdNo().equals("000000000000000000")||member.getApproveStatus()==null
				    		||member.getApproveStatus() == BizEnum.ApproveStatus.UnVerify.getType()){	
				    	member.setIdNo(certNo);
				    	member.setName(accName);
				    	member.setApproveStatus(BizEnum.ApproveStatus.Verified.getType());
				    	memberMapper.updateByPrimaryKeySelective(member);
				    	String email=member.getUserId()+"@163.com"; 
					    PayUpdateData ud=PayUpdateData.initialize(
								member.getPayGroupCode(), 
								member.getVirtualCard(), 
								accName, 
								mobile,
								certNo, 
								DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
								email,
								null,
								"01",null);//01表示用户正常  00表示用户禁用
					    PayResult payResult=IPayAPI.updateAccountData(ud);
					    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
					    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
					    }
					    logger.info("=================================认证信息修改成功==================================="); 
				    }
				  //快捷卡已认证 不需要重复认证
		}else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.QuickPayCard.getType())&&memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			throw new ApplicationException(Rescode.FAIL, "该卡已认证，无需重复认证");
			//未成功认证快捷卡
		}else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.QuickPayCard.getType())&&!memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			memberCard.setGmtCreate(new Date());
			memberCard.setGmtModified(new Date());
			memberCard.setMemberId(Long.parseLong(memberId));
			memberCard.setBankIntegral(bankCode);
			memberCard.setCardNum(accNo);
			memberCard.setIdName(accName);
			memberCard.setIdNo(certNo);
			memberCard.setCardMobile(mobile);
			memberCard.setCardType(cardType); 
			memberCard.setCardCvn(cardCvn);
			memberCard.setCardExpdate(cardExpdate);
			memberCard.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
			memberCard.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
			memberCard.setBankZone(null);//开户地区
			memberCardMapper.updateByPrimaryKey(memberCard);
			result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
			//未成功认证提现卡
		 }else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())&&!memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			    memberCard.setGmtCreate(new Date());
				memberCard.setGmtModified(new Date());
				memberCard.setMemberId(Long.parseLong(memberId));
				memberCard.setBankIntegral(bankCode);
				memberCard.setCardNum(accNo);
				memberCard.setIdName(accName);
				memberCard.setIdNo(certNo);
				memberCard.setCardMobile(mobile);
				memberCard.setCardType(cardType); 
				memberCard.setCardCvn(cardCvn);
				memberCard.setCardExpdate(cardExpdate);
				memberCard.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
				memberCard.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
				memberCard.setBankZone(null);//开户地区
				memberCardMapper.updateByPrimaryKey(memberCard);
				result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
				//已经成功认证提现卡
		 }else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())&&memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			      if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())){
			    	  Const.CacheMap.put(Const.SysOrderNum_PHONE+memberId, mobile);
					if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){
						 //信用卡 需要添加有效期 cvn 信息    cardCvn,  cardExpdate
						 Const.CacheMap.put(Const.SysOrderNum_cardCvn+memberId, cardCvn);
						 Const.CacheMap.put(Const.SysOrderNum_cardExpdate+memberId, cardExpdate);
					}
				}
   //			 String mobile, String cardCvn, String cardExpdate
				result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
		 }
		String orgOrderNum = UtilFun.createOrderNum(Const.APP_RECHARGE);
		Date date=new Date();
	//	String payOrderid=Const.APP_RECHARGE+orgOrderNum;
		TradeOffline tradeOffline=AddtradeOffline(member,date,tranAmt,orgOrderNum,accNo,orgOrderNum);
		try {
			tradeOfflineMapper.insertSelective(tradeOffline);
		} catch (Exception e) {
			throw new ApplicationException(Rescode.FAIL, "线上记录保存异常");
		}
		PayQuickPaymentRecharge payQuickPaymentRecharge=PayQuickPaymentRecharge.initialize(
				member.getPayGroupCode(), 
				member.getVirtualCard(), 
				tranAmt,
				bankCode, 
				"156",
				accName,
				accNo,
				certNo, 
				mobile, 
				"app快捷绑卡", 
				DateUtil.fomatDate(date,DateUtil.sdfTimes),
				orgOrderNum,
				"1", 
				orgOrderNum, 
				cvnStr,ip);
		PayResult payResult = IPayAPI.userQuickPaymentRecharge(payQuickPaymentRecharge);
	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
	Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
	Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
	Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
	Const.CacheMap.put(Const.cardNum_CODE+memberId, accNo);
	Const.CacheMap.put(Const.bankCode_CODE+memberId, bankCode);
	result.put("tranAmt", tranAmt);//返回卡id 便于重复发送验证码
	return result;
	}
	
	public void bankDesc(MemberCard record,String bankCode) { 
		switch (bankCode) {
		case "0801020000":
			record.setIssuerBankName("工商银行");
			break;
		case "0801030000":
			record.setIssuerBankName("农业银行");
			break;
		case "0801040000":
			record.setIssuerBankName("中国银行");
			break;
		case "0801050000":
			record.setIssuerBankName("建设银行");
			break;
		case "0801000000":
			record.setIssuerBankName("邮政储蓄银行");
			break;
		case "0804100000":
			record.setIssuerBankName("平安银行");
			break;
		case "0803050000":
			record.setIssuerBankName("民生银行");
			break;
		case "0803030000":
			record.setIssuerBankName("光大银行");
			break;
		case "0803060000":
			record.setIssuerBankName("广发银行");
			break;
		case "0863020000"://0803020000
			record.setIssuerBankName("中信银行");
			break;
		case "0803090000":
			record.setIssuerBankName("兴业银行");
			break;
		case "0803040000":
			record.setIssuerBankName("华夏银行");
			break;
		case "0803080000":
			record.setIssuerBankName("招商银行");
			break;
		case "0803100000":
			record.setIssuerBankName("浦发银行");
			break;
		case "0803010000":
			record.setIssuerBankName("交通银行");
			break;
		case "0804031000":
			record.setIssuerBankName("北京银行");
			break;
		case "0804012900":
			record.setIssuerBankName("上海银行");
			break;
		case "0804023930":
			record.setIssuerBankName("厦门银行");
			break;	
		default:
			record.setIssuerBankName(null);
			break;
		}
	}
	
	public static TradeOffline AddtradeOffline(Member member,Date date,String tranAmt,String orgOrderNum,String accNo,String payOrderid){
		 TradeOffline tradeOffline=new TradeOffline();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(member.getGroupId());
		    tradeOffline.setOrderId(orgOrderNum);
		    tradeOffline.setPayerId(member.getId());//付款者id号
		    tradeOffline.setPayerName(member.getName());//付款者姓名
		    tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());//支付方式 生成订单支付方式未知
		    tradeOffline.setReceiverId(null);//接收者id
		    tradeOffline.setReceiverName(null);//接收者 此处以核销录入数据
		    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Recharge.getType());//交易类型
		    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(Integer.valueOf(tranAmt)); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(Integer.valueOf(tranAmt));//实付金额
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());//交易状态
		    tradeOffline.setIsWallet(false);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMemo("云流钱包充值");
		    tradeOffline.setDetail("云流钱包充值待支付");
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount(accNo);//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setPayOrderid(payOrderid);//钱包充值
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构
		return tradeOffline;
		
	}

	@Override
	public Map<String, Object> updatebankcardsubmit(String memberId, String code, String ip)
			throws ApplicationException {
		Map<String, Object> result = new HashMap<String, Object>();
		String SysOrderNum=Const.CacheMap.get(Const.SysOrderNum_CODE+memberId);
		String paySign=Const.CacheMap.get(Const.PaySign_CODE+memberId);
		String ThirdOrderNum=Const.CacheMap.get(Const.ThirdOrderNum_CODE+memberId);
		String cardNum=Const.CacheMap.get(Const.cardNum_CODE+memberId);
		String bankCode=Const.CacheMap.get(Const.bankCode_CODE+memberId);
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(Tools.isEmpty(SysOrderNum)||Tools.isEmpty(paySign)||Tools.isEmpty(ThirdOrderNum)){
			throw new ApplicationException(Rescode.FAIL, "未填写资料信息");
		}
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectCardNum(Long.parseLong(memberId),cardNum,bankCode);
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "卡信息不存在");
		}
		if(memberCard.getCardStatus().equals(BizEnum.CardStatus.UnVerify.getType())){
			memberCard.setCardStatus(BizEnum.CardStatus.Verified.getType()); 
			memberCardMapper.updateByPrimaryKey(memberCard);
		}
		//提现卡-更改为快捷卡
		if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())){
			memberCard.setCardStatus(BizEnum.CardStatus.Verified.getType()); 
			memberCard.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
			memberCard.setCardMobile(Const.CacheMap.get(Const.SysOrderNum_PHONE+memberId)); 
			if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){
				 //信用卡 需要添加有效期  cardExpdate cvn 信息
				memberCard.setCardCvn(Const.CacheMap.get(Const.SysOrderNum_cardCvn+memberId)); 
				memberCard.setCardExpdate(Const.CacheMap.get(Const.SysOrderNum_cardExpdate+memberId)); 
			}
			memberCardMapper.updateByPrimaryKey(memberCard);
		}
		String orgOrderNum = UtilFun.createOrderNum();
		PayQuickPaymentRechargeSubmit qprs=PayQuickPaymentRechargeSubmit.initialize(member.getPayGroupCode(), member.getVirtualCard(), SysOrderNum, null, code,
				ThirdOrderNum, paySign, memberCard.getCardMobile(), memberCard.getCardNum(), orgOrderNum, ip);
		PayResult payResult=IPayAPI.userQuickPaymentRechargeSubmit(qprs);
		if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		return result;
	}

	@Override
	public Map<String, Object> updateExistCardsubmit(String memberId, String ip, String cardId, String tranAmt)
			throws ApplicationException {
		Map<String, Object> result = new HashMap<String, Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		String cvnStr=null;
		//此处调用绑卡接口
		if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){ 
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}
		String orgOrderNum = UtilFun.createOrderNum(Const.APP_RECHARGE);
		Date date=new Date();
	//	String payOrderid=Const.APP_RECHARGE+orgOrderNum;
		TradeOffline tradeOffline=AddtradeOffline(member,date,tranAmt,orgOrderNum,memberCard.getCardNum(),orgOrderNum);
		tradeOfflineMapper.insertSelective(tradeOffline);
		PayQuickPaymentRecharge payQuickPaymentRecharge=PayQuickPaymentRecharge.initialize(
				member.getPayGroupCode(), 
				member.getVirtualCard(), 
				tranAmt,
				memberCard.getBankIntegral(), 
				"156",
				memberCard.getIdName(),
				memberCard.getCardNum(),
				memberCard.getIdNo(), 
				memberCard.getCardMobile(), 
				"app快捷绑卡", 
				DateUtil.fomatDate(date,DateUtil.sdfTimes),
				orgOrderNum,
				"1", 
				orgOrderNum, 
				cvnStr,ip);
		PayResult payResult = IPayAPI.userQuickPaymentRecharge(payQuickPaymentRecharge);
	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
	    result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
	    result.put("tranAmt", tranAmt);//返回卡id 便于重复发送验证码
	    Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		Const.CacheMap.put(Const.cardNum_CODE+memberId, memberCard.getCardNum());
		Const.CacheMap.put(Const.bankCode_CODE+memberId, memberCard.getBankIntegral());
		return result;
	}

	

	@Override
	public Response updateWeiXinGoodsPay(String memberId, Integer goodsOrderPrice, String orderId, String ip,
			String homeUrl) throws ApplicationException {
		Map<String, Object> result = new HashMap<String, Object>();
		Member member=memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
		if (member==null) {
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		if (groupPayconfig==null) {
			throw new ApplicationException(Rescode.FAIL, "商户参数未配置");
		}
		OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId,BizEnum.MallOrderStatus.WaitingForPay.getType());
		if (orderGood==null) {
			throw new ApplicationException(Rescode.FAIL, "未查询到该商品订单");
		}
		//查询是否有该笔订单记录      
	     TradeOffline tradeOffline=tradeOfflineMapper.selectByOrderIdStatus(orderId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());  
	     String orgOrderNum = Const.APP_CONSUME+UtilFun.createOrderNum();
	     if(tradeOffline!=null){
			tradeOffline.setMemo("微信消费购买");
      		tradeOffline.setDetail("微信消费购买");//详情
      		tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());//orgOrderNum
      		tradeOffline.setPayOrderid(orgOrderNum);//CZH app微信消费
      		tradeOffline.setPayType((byte)BizEnum.PaymentType.WebChat.getType());
		    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

			 try {
				 //profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
				 memberService.insertMemberTradeDataAsyn(member.getId(),tradeOffline.getRealAmount());
			 } catch (Exception e) {
				 e.printStackTrace();
			 }
		}else{
			throw new ApplicationException(Rescode.FAIL,"未查询到未支付的订单");
		}
	    //微信原生支付调用
		WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
		String nonce_str = RandomStringUtils.randomAlphanumeric(28);
		orderRequest.setNonceStr(nonce_str);
		orderRequest.setDeviceInfo("WEB");
		orderRequest.setBody("微信购买商品");
		orderRequest.setOutTradeNo(orgOrderNum);
		orderRequest.setTotalFee(goodsOrderPrice);// 单位分
		orderRequest.setSpbillCreateIp(ip);// IP
		orderRequest.setNotifyURL(homeUrl+Const.WXCHARGE_NOTIFY_URL);//回调地址
		orderRequest.setTradeType("APP");// JSAPI，NATIVE，APP，WAP
		WxPayService wxPayService = new WxPayServiceImpl(); 
		WxPayConfig wxPayConfig=new WxPayConfig();
		wxPayConfig.setAppId(groupPayconfig.getWxAppid()); 
		wxPayConfig.setMchId(groupPayconfig.getWxMerchantno()); 
		wxPayConfig.setMchKey(groupPayconfig.getWxPayKey());
		wxPayService.setConfig(wxPayConfig);
		try {
			WxPayUnifiedOrderResult unifiedorderResult = wxPayService.unifiedOrder(orderRequest);
			if ("SUCCESS".equals(unifiedorderResult.getReturnCode())) {
				if ("SUCCESS".equals(unifiedorderResult.getResultCode())) {
					result.put("appid", unifiedorderResult.getAppid());
					result.put("mch_id", unifiedorderResult.getMchId());
					result.put("nonce_str", unifiedorderResult.getNonceStr());
					result.put("sign", unifiedorderResult.getSign());
					result.put("prepay_id", unifiedorderResult.getPrepayId());
					result.put("trade_type", unifiedorderResult.getTradeType());
					result.put("orgOrderNum", orgOrderNum);
					result.put("orderAmount", goodsOrderPrice);
					return Response.getSuccess(result); 
				} else {
					throw new ApplicationException(unifiedorderResult.getResultCode(), unifiedorderResult.getErrCodeDes());
				}
			}
		} catch (WxErrorException e) {
			throw new ApplicationException(Rescode.FAIL, "统一下单出现异常");
		}
		return null;
	}

	@Override
	public Response updateAliGoodsPay(String memberId, Integer goodsOrderPrice,String orderId) throws ApplicationException {
		Member member=memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
		if (member==null) {
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		if (groupPayconfig==null) {
			throw new ApplicationException(Rescode.FAIL, "商户参数未配置");
		}
		OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId,BizEnum.ServiceOrderStatus.WaitingForPay.getType());
		if (orderGood==null) {
			throw new ApplicationException(Rescode.FAIL, "未查询到该商品订单");
		}
		//查询是否有该笔订单记录      
	     TradeOffline tradeOffline=tradeOfflineMapper.selectByOrderIdStatus(orderId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());  
	     String orgOrderNum = Const.APP_CONSUME+UtilFun.createOrderNum();
	     if(tradeOffline!=null){
			tradeOffline.setMemo("支付宝消费购买");
      		tradeOffline.setDetail("支付宝消费购买");//详情
      		tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
      		tradeOffline.setPayOrderid(orgOrderNum);
      		tradeOffline.setPayType((byte)BizEnum.PaymentType.AliPay.getType());
		    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

//			 try {
//				 //profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
//				 memberService.insertMemberTradeDataAsyn(member.getId(),tradeOffline.getRealAmount());
//			 } catch (Exception e) {
//				 e.printStackTrace();
//			 }
		}else{
			throw new ApplicationException(Rescode.FAIL,"未查询到该笔订单");
		}
	     return Response.getSuccess(orgOrderNum);
	}

	@Override
	public Response updateGoodsOrderPay(String memberId, String orderId,String payPwd,Integer price)
			throws ApplicationException {
		  Member member=memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
		    if(member==null){ 
		    	throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		    }
		    String orgOrderNum=Const.APP_CONSUME+UtilFun.createOrderNum();
			Date date=new Date();
			//兼容老用户
			if(member.getTradePassword().equals("888888")){
					member.setTradePassword(AES.AESEncode(Const.AceKey, payPwd));  
					memberMapper.updateByPrimaryKeySelective(member);
			}else{
				if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
					throw new ApplicationException(Rescode.FAIL, "支付密码错误");
				}
			}
			
			OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId,BizEnum.ServiceOrderStatus.WaitingForPay.getType());
			if(orderGood!=null){
			    TradeOffline tradeOffline=tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte)BizEnum.TransactionStatus.WaitingForPay.getType());
			    if(tradeOffline==null){ 
			    	throw new ApplicationException(Rescode.FAIL, "订单信息不存在");
			    }
			    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());//交易状态
			    tradeOffline.setPayOrderid(orgOrderNum);//支付平台订单号
			    tradeOffline.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
			    tradeOffline.setIsWallet(true);//钱包交易  
			    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
			    //更改商品订单状态
			    orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType()); 
				orderGoodMapper.updateByPrimaryKey(orderGood);
			    //调用支付平台消费接口
			    Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
			    
			    PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),
						 tradeOffline.getRealAmount(), orderId, payPwd,null,tradeOffline.getOrderId());
					if (!payResult.getRespCode().equals("0000")) {
						throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
					}
			    
			    Map<String, Object> map = new HashMap<String, Object>();
			    SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				map.put("orderDate",sdfTime.format(date));
				map.put("orderStateName",BizEnum.TransactionStatus.Success.getName());
				map.put("orderId",orderId);
				map.put("tradeOffline", tradeOffline);
				map.put("orgOrderNum", orgOrderNum);

				try {
					//profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
					memberService.insertMemberTradeDataAsyn(member.getId(),tradeOffline.getRealAmount());
				} catch (Exception e) {
					e.printStackTrace();
				}

			    return Response.getSuccessExtend(map,orgOrderNum);
			}else{
				throw new ApplicationException(Rescode.FAIL, "未发现待付款的订单");
			}
	}

	@Override
	public Map<String, Object> insertbankGoodsPay(String memberId, String tranAmt, String bankCode, String accNo,
			String accName, String certNo, String mobile, String cardCvn, String cardExpdate, String ip,String orderId) throws ApplicationException {
			Map<String, Object> result = new HashMap<String, Object>();
			Member member = memberMapper.queryGroup(Long.parseLong(memberId));
			if(member==null){
				throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
			}
			//校验卡是否支持绑定 提高绑卡成功率  
			Map<String, String> mapCardNum=IPayAPI.queryCardCodeNew(accNo);
			if(!mapCardNum.get("Rcd").equals("0000")){
				throw new ApplicationException(Rescode.FAIL, "该卡暂不支持快捷绑定,请换张卡再试");
			}
			if(!mapCardNum.get("InsCd").equals(bankCode)){
				throw new ApplicationException(Rescode.FAIL, "您输入的卡号是"+mapCardNum.get("Cnm"));
			}
			MemberCard memberCardName=memberCardMapper.selectByPrimaryName(Long.parseLong(memberId));
			if(memberCardName!=null&&!memberCardName.getIdName().equals(accName)){
				throw new ApplicationException(Rescode.FAIL, "此卡认证信息与初次认证信息不匹配");
			}
			
			int cardType=BizEnum.CardType.DebitCard.getType();
			String cvnStr=null;
			//此处调用绑卡接口
			if(Tools.notEmpty(cardCvn)&&Tools.notEmpty(cardExpdate)){
				cardType=BizEnum.CardType.CreditCard.getType();
				cvnStr=cardCvn+";"+cardExpdate;
			}
			
			//验证该卡是否绑定过
			MemberCard memberCard =  memberCardMapper.selectCardNum(Long.parseLong(memberId),accNo,bankCode);
			if(memberCard==null){
				MemberCard record = new MemberCard();
				record.setGmtCreate(new Date());
				record.setGmtModified(new Date());
				record.setMemberId(Long.parseLong(memberId));
				record.setBankIntegral(bankCode);
				record.setCardNum(accNo);
				record.setIdName(accName);
				record.setIdNo(certNo);
				record.setCardMobile(mobile);
				record.setCardType(cardType); 
				record.setCardCvn(cardCvn);
				record.setCardExpdate(cardExpdate);
				record.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
				record.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
				record.setBankZone(null);//开户地区
				bankDesc(record, bankCode); 
			    memberCardMapper.insert(record);
			    result.put("cardId", record.getId());//返回卡id 便于重复发送验证码
					    if(member.getIdNo().equals("000000000000000000")||member.getApproveStatus()==null
					    		||member.getApproveStatus() == BizEnum.ApproveStatus.UnVerify.getType()){	
					    	member.setIdNo(certNo);
					    	member.setName(accName);
					    	member.setApproveStatus(BizEnum.ApproveStatus.Verified.getType());
					    	memberMapper.updateByPrimaryKeySelective(member);
					    	String email=member.getUserId()+"@163.com"; 
						    PayUpdateData ud=PayUpdateData.initialize(
									member.getPayGroupCode(), 
									member.getVirtualCard(), 
									accName, 
									mobile,
									certNo, 
									DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
									email,
									null,
									"01",null);//01表示用户正常  00表示用户禁用
						    PayResult payResult=IPayAPI.updateAccountData(ud);
						    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
						    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
						    }
						    logger.info("=================================认证信息修改成功==================================="); 
					    }
					  //快捷卡已认证 不需要重复认证
			}else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.QuickPayCard.getType())&&memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
				throw new ApplicationException(Rescode.FAIL, "该卡已认证，无需重复认证");
				//未成功认证快捷卡
			}else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.QuickPayCard.getType())&&!memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
				memberCard.setGmtCreate(new Date());
				memberCard.setGmtModified(new Date());
				memberCard.setMemberId(Long.parseLong(memberId));
				memberCard.setBankIntegral(bankCode);
				memberCard.setCardNum(accNo);
				memberCard.setIdName(accName);
				memberCard.setIdNo(certNo);
				memberCard.setCardMobile(mobile);
				memberCard.setCardType(cardType); 
				memberCard.setCardCvn(cardCvn);
				memberCard.setCardExpdate(cardExpdate);
				memberCard.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
				memberCard.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
				memberCard.setBankZone(null);//开户地区
				memberCardMapper.updateByPrimaryKey(memberCard);
				result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
				//未成功认证提现卡
			 }else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())&&!memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
				    memberCard.setGmtCreate(new Date());
					memberCard.setGmtModified(new Date());
					memberCard.setMemberId(Long.parseLong(memberId));
					memberCard.setBankIntegral(bankCode);
					memberCard.setCardNum(accNo);
					memberCard.setIdName(accName);
					memberCard.setIdNo(certNo);
					memberCard.setCardMobile(mobile);
					memberCard.setCardType(cardType); 
					memberCard.setCardCvn(cardCvn);
					memberCard.setCardExpdate(cardExpdate);
					memberCard.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
					memberCard.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
					memberCard.setBankZone(null);//开户地区
					memberCardMapper.updateByPrimaryKey(memberCard);
					result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
					//已经成功认证提现卡
			 }else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())&&memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
				      if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())){
				    	  Const.CacheMap.put(Const.SysOrderNum_PHONE+memberId, mobile);
						if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){
							 //信用卡 需要添加有效期 cvn 信息    cardCvn,  cardExpdate
							 Const.CacheMap.put(Const.SysOrderNum_cardCvn+memberId, cardCvn);
							 Const.CacheMap.put(Const.SysOrderNum_cardExpdate+memberId, cardExpdate);
						}
					}
					result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
			 }
			OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId,BizEnum.ServiceOrderStatus.WaitingForPay.getType());
			if(orderGood==null){
				throw new ApplicationException(Rescode.FAIL,"未发现待付款的订单");
			}
		    String orgOrderNum=Const.APP_CONSUME+UtilFun.createOrderNum();
		    TradeOffline record=tradeOfflineMapper.selectByOrderIdStatus(orderId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());        
	  	       if(record!=null){
	  	    	    record.setMemo("银行卡快捷消费");
	  	    	    record.setDetail("app银行卡快捷支付消费购买");//详情
	  	    	    record.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
	  	    	    record.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
	  	    	    record.setPayOrderid(orgOrderNum); 
	 		        tradeOfflineMapper.updateByPrimaryKeySelective(record);
		  	    	PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
		      	    		member.getPayGroupCode(), 
		      				member.getVirtualCard(), 
		      				tranAmt,
		      				bankCode, 
		      				"156",
		      				accName,
		      				accNo,
		      				certNo, 
		      				mobile, 
		      				"快捷绑卡消费", 
		      				DateUtil.fomatDate(new Date(),DateUtil.sdfTimes),
		      				orgOrderNum,
		      				"1", 
		      				orgOrderNum, 
		      				cvnStr,ip);
		  	    	PayResult   payResult =IPayAPI.userQuickPayment(payQuickPaymentPay);
		      	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
		      	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
		      	    }
		      	Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		  		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		  		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		  		Const.CacheMap.put(Const.cardNum_CODE+memberId, accNo);
		  		Const.CacheMap.put(Const.bankCode_CODE+memberId, bankCode);
		  		result.put("tranAmt", tranAmt);//返回卡id 便于重复发送验证码
	  	       	}else{
		  	   throw new ApplicationException(Rescode.FAIL,"未查询到未支付的订单");
		     }
				return result;
		
	}

	@Override
	public Map<String, Object> updateExistBankGoodsPay(String memberId, String ip, String cardId, String tranAmt,
			String orderId) throws ApplicationException {
		Map<String, Object> result = new HashMap<String, Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		String cvnStr=null;
		//此处调用绑卡接口
		if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){ 
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}
		OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId,BizEnum.ServiceOrderStatus.WaitingForPay.getType());
		if(orderGood==null){
			throw new ApplicationException(Rescode.FAIL,"未发现待付款的订单");
		}
		String orgOrderNum=Const.APP_CONSUME+UtilFun.createOrderNum();
	    TradeOffline record=tradeOfflineMapper.selectByOrderIdStatus(orderId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());        
  	       if(record!=null){
  	    	    record.setMemo("银行卡快捷消费");
  	    	    record.setDetail("app银行卡快捷支付消费购买");//详情
  	    	    record.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
  	    	    record.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
  	    	    record.setPayOrderid(orgOrderNum); 
 		        tradeOfflineMapper.updateByPrimaryKeySelective(record);
	  	    	PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
	      	    		member.getPayGroupCode(), 
	      				member.getVirtualCard(), 
	      				tranAmt,
	    				memberCard.getBankIntegral(), 
	    				"156",
	    				memberCard.getIdName(),
	    				memberCard.getCardNum(),
	    				memberCard.getIdNo(), 
	    				memberCard.getCardMobile(), 
	      				"快捷绑卡消费", 
	      				DateUtil.fomatDate(new Date(),DateUtil.sdfTimes),
	      				orgOrderNum,
	      				"1", 
	      				orgOrderNum, 
	      				cvnStr,ip);
	  	    	PayResult   payResult =IPayAPI.userQuickPayment(payQuickPaymentPay);
	      	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	      	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	      	    }
	    result.put("cardId", memberCard.getId());//返回卡id 便于重复发送验证码
	    result.put("tranAmt", tranAmt);//返回卡id 便于重复发送验证码
	    Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		Const.CacheMap.put(Const.cardNum_CODE+memberId, memberCard.getCardNum());
		Const.CacheMap.put(Const.bankCode_CODE+memberId, memberCard.getBankIntegral());
      	   		}
  	       else{
      		 throw new ApplicationException(Rescode.FAIL,"未发现未完成订单");
      	   }
		return result;
	}

	@Override
	public HashMap<String, Object> updateApplyWithdraw(String memberId, Integer tranAmt, String cardId, String payPwd,Integer fee)
			throws ApplicationException {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade==null||memberGrade.getWalletCanConsume()==false){
			throw new ApplicationException(Rescode.FAIL, "提现申请失败,您的帐户未获得提现权限");
		}
		//兼容老用户
				if(member.getTradePassword().equals("888888")){
					member.setTradePassword(AES.AESEncode(Const.AceKey, payPwd));  
					memberMapper.updateByPrimaryKeySelective(member);
				}else{
					if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
						throw new ApplicationException(Rescode.FAIL, "支付密码错误");
					}
				}
		String orgOrderNum=null;
		Date date=new Date();
		 TradeOffline tradeOffline=new TradeOffline();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(member.getGroupId());
		    tradeOffline.setOrderId(UtilFun.createOrderNum());
		    tradeOffline.setPayerId(member.getId());//付款者id号
		    tradeOffline.setPayerName(member.getName());//付款者姓名
		    tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setPayType((byte)BizEnum.PaymentType.Wallet.getType());//支付方式 生成订单支付方式未知
		    tradeOffline.setReceiverId(null);//接收者id        
		    tradeOffline.setReceiverName(null);//接收者 此处以核销录入数据
		    if(memberCard.getCardType()==BizEnum.CardType.DebitCard.getType()){
		    	tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Withdraw.getType());//交易类型
		    	tradeOffline.setMemo("用户申请提现");
			    tradeOffline.setDetail("云流钱包用户申请提现");
			    orgOrderNum=Const.APP_WITHDEAW+UtilFun.createOrderNum();
			    tradeOffline.setPayOrderid(orgOrderNum);
		    }else if(memberCard.getCardType()==BizEnum.CardType.CreditCard.getType()){
		    	 tradeOffline.setTransactionType((byte)BizEnum.TransactionType.CreditCardRepay.getType());//交易类型
		    	 tradeOffline.setMemo("用户信用卡还款");
				 tradeOffline.setDetail("云流钱包用户信用卡还款");
				 orgOrderNum=Const.APP_REPAYMENT+UtilFun.createOrderNum(); 
				 tradeOffline.setPayOrderid(orgOrderNum);
		    }
		//    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(tranAmt); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(tranAmt+fee);//提现实付金额=提现金额+手续费
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Proccessing.getType());//交易状态
		    tradeOffline.setIsWallet(true);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount(memberCard.getCardNum());//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构
		    tradeOffline.setFee(fee); 
		    tradeOfflineMapper.insertSelective(tradeOffline);
		    hashMap.put("member", member);
		    hashMap.put("memberCard", memberCard);
		    hashMap.put("memberGrade", memberGrade);
		    hashMap.put("orgOrderNum", orgOrderNum);
			return hashMap;
	}
	
	@Override
	public Response sendApplyWithdraw(HashMap<String, Object> hashMap, Integer tranAmt,String payPwd,Integer fee)
			throws ApplicationException {
		Map<String, Object> map = new HashMap<String, Object>();
		Member member = (Member) hashMap.get("member");
		MemberCard memberCard =  (MemberCard) hashMap.get("memberCard");
//		MemberGrade memberGrade=(MemberGrade) hashMap.get("memberGrade");
		String orgOrderNum=hashMap.get("orgOrderNum").toString();
		
		PayWithdrawalResult result =walletService.updateBankWithdrawal(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(), tranAmt,
				orgOrderNum, payPwd, memberCard.getCardNum(), memberCard.getBankIntegral(), memberCard.getIdName(), memberCard.getIssuerBankName(), fee);
		
		if(result==null || result.getVerificationStatus().byteValue()==0x00){
			logger.info(PayWithdrawalResult.getNotNullMsgTxt(result, "提现申请提交失败,通信异常"));
			throw new ApplicationException(Rescode.FAIL, "提现申请提交失败,通信异常");
		}else{
			if(Rescode.SUCCESS.equals(result.getRespCode())){
				map.put("actualAt", result.getActualAt());
				map.put("status", result.getStatus());
				map.put("feeAt", result.getFeeAt());
				map.put("orderId", result.getOrderId());
				map.put("msgTxt", result.getMsgTxt());
			   return Response.getSuccess(map);
			}else{
				logger.info("提现异常描述:"+result.getMsgTxt());
				throw new ApplicationException(result.getRespCode(), result.getMsgTxt());
			}
		}
		    
	}
	
	

	@Override
	public Map<String, Object> insertUserTransfer(String memberId, String phone, String toMemberId, String amount,
			String password) throws ApplicationException {
		String orgOrderNum = Const.APP_TRANSFER+UtilFun.createOrderNum();
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		Member toMember=memberMapper.selectByPrimaryPhone(member.getGroupId(),phone,null);
		if(toMember==null||toMember==null){
			throw new ApplicationException(Rescode.FAIL,"转出方信息不存在");
		}
		//判断双方是否都进行实名认证 未认证不能转账支付
//		if(member.getIdNo().equals("000000000000000000") || member.getApproveStatus() == 0){
//			throw new ApplicationException(Rescode.FAIL,"您的信息未实名支付认证");
//		}
//		if(toMember.getIdNo().equals("000000000000000000") || toMember.getApproveStatus() == 0){
//			throw new ApplicationException(Rescode.FAIL,"对方信息未实名支付认证");
//		}
		//兼容老用户
				if(member.getTradePassword().equals("888888")){
						member.setTradePassword(AES.AESEncode(Const.AceKey, password));  
						memberMapper.updateByPrimaryKeySelective(member);
				}else{
					if (!AES.AESEncode(Const.AceKey, password).equals(member.getTradePassword())) {
						throw new ApplicationException(Rescode.FAIL, "支付密码错误");
					}
				}
		Date date=new Date();
		TradeOffline tradeOffline=new TradeOffline();
	    tradeOffline.setGmtCreate(date);
	    tradeOffline.setGmtModified(date);
	    tradeOffline.setGroupId(member.getGroupId());
	    tradeOffline.setOrderId(UtilFun.createOrderNum());
	    tradeOffline.setPayerId(member.getId());//付款者id号
	    tradeOffline.setPayerName(member.getName());//付款者姓名
		tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
	    tradeOffline.setPayType((byte)BizEnum.PaymentType.Wallet.getType());//支付方式 生成订单支付方式未知
	    tradeOffline.setReceiverId(toMember.getId()+"");//接收者id
	    tradeOffline.setReceiverName(toMember.getName());//接收者
	    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Transfer.getType());//交易类型
	    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
	    tradeOffline.setOrderAmount(Integer.valueOf(amount)); //订单金额
	    tradeOffline.setDiscountAmount(0);//折扣金额
	    tradeOffline.setRealAmount(Integer.valueOf(amount));//实付金额
	    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());//交易状态
	    tradeOffline.setIsWallet(true);
	    tradeOffline.setGoodType(null);//商品类型(线上用) ？
	    tradeOffline.setMemo("app用户钱包转账");
	    tradeOffline.setDetail("app用户钱包转账");
	    tradeOffline.setMerchantNo(null);//商户号(对账用)
	    tradeOffline.setTerminalNo(null);//商户终端号
	    tradeOffline.setPayAccount(member.getVirtualCard());//支付卡号
	    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
	    tradeOffline.setCrcodeStr(null); 
	    tradeOffline.setOldOrderId(null); 
	    tradeOffline.setDividableAmount(0);//可分润金额
	    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
	    tradeOffline.setPayOrderid(orgOrderNum);//钱包充值
	    tradeOffline.setPayBakOrderid(null);
	    tradeOffline.setInNetCompany(null);//入网机构
	    tradeOfflineMapper.insertSelective(tradeOffline);
//		PayTransfer payTransfer = PayTransfer.initialize(member.getVirtualCard(),password,member.getPayGroupCode(),
//				orgOrderNum,toMember.getVirtualCard(),DateUtil.fomatDate(date,DateUtil.sdfTimes),
//				orgOrderNum,amount,"156",toMember.getName(),null);
//		PayTransferResult payTransferResult = IPayAPI.consumptionTransfer(payTransfer);
		
	    PayTransferResult payTransferResult = walletService.updateConsumptionTransfer(member.getVirtualCard(), toMember.getVirtualCard(), toMember.getName(), member.getPayGroupCode(), 
				member.getUserId(), toMember.getUserId(), Integer.valueOf(amount), null, orgOrderNum, password);
		
		
		if(!payTransferResult.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL,payTransferResult.getMsgTxt());
		}
		param.put("transferOrderNum", orgOrderNum);
		param.put("transferOrderTime", DateUtil.fomatDate(date,DateUtil.sdfTime));
        param.put("transferTranAmt", payTransferResult.getActualAt());
        param.put("transferToUserid", toMember.getCardNo());  
        param.put("transferToUsername", toMember.getName()); 
		return param;
	}

	@Override
	public Response selectTransferAnnal(String memberId) throws ApplicationException {
		List<Member> list=memberMapper.selectTransferAnnal(Long.valueOf(memberId));
		List<HashMap<String, Object>>  transferAnnal=new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String,Object> param=new HashMap<String,Object>();
			param.put("name", list.get(i).getName());
			param.put("phone", list.get(i).getPhone());
			param.put("picture", list.get(i).getPicture());
			transferAnnal.add(param);
		}
		return Response.getSuccess(transferAnnal);
	}

	@Override
	public Boolean updateVerified(String memberId, String idNo, String name) throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		member.setIdNo(idNo);
		member.setName(name);
		member.setApproveStatus(1);
		memberMapper.updateByPrimaryKeySelective(member);
		String email=member.getUserId()+"@163.com"; 
	    PayUpdateData ud=PayUpdateData.initialize(
				member.getPayGroupCode(), 
				member.getVirtualCard(), 
				name, 
				member.getPhone(),
				idNo, 
				DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
				email,
				null,
				null,"1");
	    PayResult payResult=IPayAPI.updateAccountData(ud);
	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		return true;
	}

	@Override
	public Boolean updateVerifiedPassword(String memberId, String idNo, String name, String password)
			throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		String oldPwd =AES.AESDncode(Const.AceKey, member.getTradePassword());
		member.setTradePassword(AES.AESEncode(Const.AceKey, password));
		member.setIdNo(idNo);
		member.setName(name);
		member.setApproveStatus(1);
		memberMapper.updateByPrimaryKeySelective(member);
		String email=member.getUserId()+"@163.com"; 
	    PayUpdateData ud=PayUpdateData.initialize(
				member.getPayGroupCode(), 
				member.getVirtualCard(), 
				name, 
				member.getPhone(),
				idNo, 
				DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
				email,
				null,
				null,"1");
	    PayResult payResult=IPayAPI.updateAccountData(ud);
	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		String sysTraceNum = DateUtil.getDays()+Tools.getRandomNum(4);//交易流水号12位
		String groupId = member.getPayGroupCode();
		String orgTranDateTime=DateUtil.getSdfTimes();
		String orgOrderNum=orgTranDateTime+Tools.getRandomNum(4);
		PayUpdatePayPwd payUpdatePayPwd=PayUpdatePayPwd.initialize(member.getVirtualCard(),
				oldPwd, password,groupId,sysTraceNum,orgTranDateTime,orgOrderNum);
		PayResult payResultPawword=IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
		if(!PayResult.SUCCESS.equals(payResultPawword.getRespCode())){
			//throw new ApplicationException(Rescode.FAIL, " 支付密码修改失败");
					FindbackPayPwd payUpdateRestPwd=FindbackPayPwd.initialize(member.getVirtualCard(),
							password,
							member.getPayGroupCode(),
							sysTraceNum, 
							orgTranDateTime,
							"000000", 
							"000000");
					PayResult payResultRest=IPayAPI.findbackAccountPayPwd(payUpdateRestPwd);
						if(!PayResult.SUCCESS.equals(payResultRest.getRespCode())){
						throw new ApplicationException(Rescode.FAIL, " 支付密码重置失败");
					}
		}
		
		return true;
	}

	@Override
	public Response updateTkWalletPay(String orgOrderNum,Integer memberId, String deskcardId,String deskcardCode, Integer tranAmt,
			Integer actualTranAmt, Integer nooffertranAmt,String payPwd) throws ApplicationException {
		Device device=deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
		if(device==null){
        return Response.getError("台卡不存在");
        }else if(!device.getDeviceStatus().equals(BizEnum.DeviceStatus.Normal.getType())){
    		 return Response.getError("台卡"+BizEnum.DeviceStatus.fromType(device.getDeviceStatus()).getName()+"请联系系统管理员");
       }
		
        Long groupId=device.getGroupId();
        TradeOffline record = new TradeOffline();
        Member member=memberMapper.queryGroup(Long.valueOf(memberId));
        if(member==null){
        	throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
			throw new ApplicationException(Rescode.FAIL, "支付密码错误");
		}
        record.setPayerId(member.getId());//会员id
	    record.setPayerName(member.getName());
           Integer actualMoney=null;
           Shop shop=shopMapper.selectByPrimaryKey(device.getShopId());
           ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(groupId, shop.getId());
           if(shopGroupRelation==null){
           	throw new ApplicationException(Rescode.FAIL, "商户配置信息不存在");
           }
           String MerchantId=null;
           PrePurchaseActivity prePurchaseActivity=null;
           if(shopGroupRelation.getPrePurchaseStatus()==1){//预采购
        	    // 表示处于预采购中
				 prePurchaseActivity = prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), groupId);
				// 查询渠道的收款账户
				if (prePurchaseActivity == null) {
					throw new ApplicationException(Rescode.FAIL, "商户状态不正确");
				}
				int acturlAmount = tranAmt * prePurchaseActivity.getCustomerBenefitAmount() / 100;
				record.setMemo("Prepurchase");
				record.setDiscountAmount(tranAmt - acturlAmount);// 折扣金额
				record.setRealAmount(acturlAmount);// 实付金额
				record.setPrepurActivityId(prePurchaseActivity.getId());
           }else{
        	   MerchantId=shopGroupRelation.getPayMerchantCode();
        	   record.setRealAmount(actualTranAmt);//实付金额
        	   record.setDiscountAmount(actualMoney==null?0:tranAmt-actualTranAmt);//折扣金额
        	   record.setMemo("钱包台卡支付");
           }
   		   record.setReceiverId(shop.getId()+"");//接收者id
		   record.setReceiverName(shop.getMerchantName());//接收者 
			//插入线下交易表
			String orderId=UtilFun.createOrderNum();
			record.setReceiverType((byte) CommonEnum.UserType.Store.getType());
			record.setGmtCreate(new Date());
	        record.setGmtModified(new Date());
	        record.setGroupId(groupId);
	        record.setOrderId(orderId); 
	        record.setPayerId(member.getId());//付款者id号
	        record.setPayerName(member.getName());//付款者姓名
		    record.setPayerType((byte)CommonEnum.UserType.User.getType());
	        record.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
	        record.setSubType((byte)BizEnum.PaymentScene.DeskCard.getType());//支付场景
	        record.setOrderAmount(tranAmt); //订单金额
	        record.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
	        record.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
	        record.setIsWallet(true);
	        record.setTermSerial(null);
	        record.setMerchantNo(null);//商户号
	        record.setTerminalNo(null);//商户终端号
	        record.setPayAccount("");//支付卡号
	        record.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
	        record.setOldOrderId(null); 
	        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
	        record.setPayBakOrderid(null);
	        record.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());//入网机构
	        record.setDetail(null);//详情
   		    record.setCrcodeStr(null);  
   		    record.setPayOrderid(orgOrderNum);
	        String SysTraceNum=DateUtil.getSdfTimes()+Tools.getRandomNum(4);
	        record.setTransNo(SysTraceNum); //交易流水号
	        PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(),
	        		actualTranAmt, orderId, payPwd,MerchantId,orderId);
				if (!payResult.getRespCode().equals("0000")) {
					throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
				}
	        
	        if(prePurchaseActivity!=null){
	        	//当前 处于预采购
	        	finishProcessPrePurchase(record, prePurchaseActivity);
	        }else{
	        	 record.setDividableAmount(SysUtils.Object2int(payResult.getMerchantFee()));//可分润金额
	        	 record.setFee(SysUtils.Object2int(payResult.getMerchantFee()));
	  	         record.setShopFee(SysUtils.Object2int(payResult.getMerchantFee())); 
	        }
	        record.setTransOrderNo(payResult.getOrderId());
	        tradeOfflineMapper.insertSelective(record);
   		    OrderShop orderShop =new OrderShop();
   		    orderShop.setAmount(tranAmt);
   		    orderShop.setGmtCreate(new Date());
   		    orderShop.setGmtModified(new Date());
   		    orderShop.setMemberId(member.getId());
   		    orderShop.setOrderId(record.getId()); 
   		    orderShop.setOrderNo(orderId);
   		    orderShop.setShopId(shop.getId());
   		    orderShop.setStatus(BizEnum.ShopOrderStatus.WaitingForComment.getType());
   		    orderShopMapper.insert(orderShop);
	        return Response.getSuccessExtend("支付成功",record);
	}
	
	
	/**
	 * 处理预采购相关逻辑
	 * 
	 * @param tradeOffline
	 */
	private void finishProcessPrePurchase(TradeOffline tradeOffline,PrePurchaseActivity prePurActivity) {

		Integer amount = tradeOffline.getOrderAmount();
		prePurActivity.setCustomerSaleAmount(prePurActivity.getCustomerSaleAmount() + tradeOffline.getOrderAmount());
		prePurActivity.setCustomerPayAmount(prePurActivity.getCustomerPayAmount() + tradeOffline.getRealAmount());
		prePurActivity.setCustomerSaleCount(prePurActivity.getCustomerSaleCount() + 1);
		String lastTradeDate = SysUtils.formatDate(prePurActivity.getLastTradeDate(), "yyyyMMDD");
		Integer merchantSetAmount = amount * prePurActivity.getAgentBenefitAmount() / 100;
		prePurActivity.setLastTradeDate(tradeOffline.getGmtCreate());
		// 设置分润
		String tradeDateStr = SysUtils.formatDate(tradeOffline.getGmtCreate(), "yyyyMMDD");
		//
		Integer profitAmount=(prePurActivity.getCustomerBenefitAmount() - prePurActivity.getAgentBenefitAmount()) * amount / 100;
		tradeOffline.setDividableAmount(profitAmount);
		tradeOffline.setFee(profitAmount);
		 tradeOffline.setShopFee(profitAmount); 
	      
		if (lastTradeDate.equals(tradeDateStr)) {
			// 表示是同一天交易
			prePurActivity.setMerchantTodayAmount(prePurActivity.getMerchantTodayAmount() + merchantSetAmount);

		} else {
			//
			prePurActivity.setMerchantLastDayAmount(prePurActivity.getMerchantTodayAmount());
			prePurActivity.setMerchantTodayAmount(merchantSetAmount);
		}
		prePurActivity.setRiskAmount(prePurActivity.getRiskAmount() + merchantSetAmount);
		System.out.println("merchantSetAmount:" + merchantSetAmount);
		prePurActivity.setGmtModified(new Date());

		if (prePurActivity.getCustomerSaleAmount() >= prePurActivity.getPrepurchaseAmount()) {
			// 这个预采购额度已经满了 ，将他结束
			prePurActivity.setEndDate(new Date());
			prePurActivity.setStatus(BizEnum.PrePurchaseActivityStatus.end.getType());
		}
		// 查询 代理商

		Agent agent = agentMapper.selectByPrimaryKey(prePurActivity.getAgentId());
		PrePurchaseMoneyChange prePurchaseMoneyChange = new PrePurchaseMoneyChange();
		prePurchaseMoneyChange.setAgentId(agent.getId());
		prePurchaseMoneyChange.setAmount(merchantSetAmount * 1L);
		prePurchaseMoneyChange.setChangeType(1);
		prePurchaseMoneyChange.setGmtCreate(new Date());
		prePurchaseMoneyChange.setGmtModified(new Date());
		prePurchaseMoneyChange.setGroupId(agent.getGroupId());
		String balanceStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance()) / 100, 2);
		String moneyStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney()) / 100, 2);
		prePurchaseMoneyChange
				.setInfoDesc("预采购活动进行中，用户消费返还可以约，返还前余额" + balanceStr + ",返还前余额额度为" + moneyStr + ",返还金额为" + SysUtils.formatNumber(merchantSetAmount / 100, 2));
		prePurchaseMoneyChange.setOperateUser("系统处理");
		prePurchaseMoneyChange.setOperateUserId(0L);
		prePurchaseMoneyChange.setType(1);// 表示渠道调整
		prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);

		agent.setPrePurchaseBalance(agent.getPrePurchaseBalance() + merchantSetAmount);
		String descMoney = SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		agent.setPrePurchaseBalanceDes(descMoney);
		agentMapper.updateByPrimaryKey(agent);

		//
		
		prePurchaseActivityMapper.updateByPrimaryKey(prePurActivity);
	}


	@Override
	public Response findMerchantName(String businessCode, String fyMerchantId, Integer memberId) throws ApplicationException {
	        Device device = deviceMapper.selectByPrimaryCode(businessCode, Long.valueOf(fyMerchantId));
	        if (device.getShopId()!= null) {
	            Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
	            //折扣比例写成固定 为100不打折扣
	            PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), device.getGroupId());
	            if(prePurchaseActivity!=null){
	            	 return Response.getSuccessExtend(shop.getMerchantName(),prePurchaseActivity.getCustomerBenefitAmount()*10);
	            }else{
	            	 return Response.getSuccessExtend(shop.getMerchantName(),"1000");
	            }
	           
	        } else { 
	        	return Response.getError("服务器异常");
	        }
	}
	
	
	@Override
	public Response findMerchantNameInfo(String deskcardId,String deskcardCode, Integer memberId) throws ApplicationException {
	        Device device = deviceMapper.selectByPrimaryCode(deskcardCode, Long.valueOf(deskcardId));
	        if(device==null){
	            return Response.getError("台卡不存在");
	            }else if(!device.getDeviceStatus().equals(BizEnum.DeviceStatus.Normal.getType())){
	        		 return Response.getError("台卡"+BizEnum.DeviceStatus.fromType(device.getDeviceStatus()).getName()+"请联系系统管理员");
	       }
	        if (device.getShopId()!= null) {
	            Shop shop = shopMapper.selectByPrimaryKey(device.getShopId());
	            Map<String, Object> map = new HashMap<String, Object>();
	            map.put("merchantName", shop.getMerchantName());
	            map.put("address", shop.getAddressProvince()+shop.getAddressCity()+shop.getAddressDistrict()+shop.getAddress());
	            PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.findInPrePurchaseActivity(device.getShopId(), device.getGroupId());
	            if(prePurchaseActivity!=null&&prePurchaseActivity.getCustomerBenefitAmount()!=null){
	            	 return Response.getSuccessExtend(map,prePurchaseActivity.getCustomerBenefitAmount()*10);
	            }else{
	            	//无折扣
	            	 return Response.getSuccessExtend(map,"1000");
	            }
	        } else { 
	        	return Response.getError("服务器异常");
	        }
	}
	
}
